package com.version.manager.controller.wx;

import com.version.manager.entity.Shop.shopUser;
import com.version.manager.model.Msg;
import com.version.manager.service.Shop.shopUserService;
import io.swagger.annotations.Api;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

@RestController
@Api(value = "WxRedirectController")
@RequestMapping("/api/shop")
public class WxRedirectController {
    @Autowired
    private  WxMpService wxService;
    @Autowired
    private shopUserService service;
    @GetMapping("/greet")
    @ResponseBody
    public Msg greetUser(@RequestParam String appid, @RequestParam String code) {
        if (!this.wxService.switchover(appid)) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", appid));
        }

        try {
            WxMpOAuth2AccessToken accessToken = wxService.oauth2getAccessToken(code);
            WxMpUser user = wxService.oauth2getUserInfo(accessToken, null);
            shopUser sUser=new shopUser();
            sUser.setHeadImgUrl(user.getHeadImgUrl());
            sUser.setNickName(user.getNickname());
            sUser.setOpenId(user.getOpenId());
            sUser.setUnionId(user.getUnionId());
            sUser.setSex(user.getSex().toString());

            return service.regist(sUser);
        } catch (WxErrorException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return Msg.fail();
    }
}
